package com.qunar.support.service;

import org.json.JSONArray;
import org.json.JSONObject;

import com.danga.MemCached.MemCachedClient;
import com.qunar.support.dao.ApplyFormDao;
import com.qunar.support.util.MemDBHelper;

/**
 * 
 * @author jinye.liu
 * 
 */
public class ApplyService {
	/**
	 * 分页获取申请
	 * 
	 * @param uid
	 * @param startIndex
	 * @param filter
	 * @return
	 */
	public JSONArray getVendorApplyByPage(int uid, long startIndex, int filter) {
		ApplyFormDao afd = new ApplyFormDao();
		JSONArray arr = null;
		if (uid != 0 && filter != 0) {
			arr = afd.getVendorApplyByPage(uid, startIndex, filter);
		} else if (uid == 0 && filter != 0) {
			arr = afd.getVendorApplyByPage(startIndex, filter);
		} else if (uid != 0 && filter == 0) {
			arr = afd.getVendorApplyByPage(uid, startIndex);
		} else if (uid == 0 && filter == 0) {
			arr = afd.getVendorApplyByPage(startIndex);
		}
		return arr;
	}

	/**
	 * 统计记录总条数
	 * 
	 * @param uid
	 * @param filter
	 * @return
	 */
	public int getVendorApplyNum(int uid, int filter) {
		ApplyFormDao afd = new ApplyFormDao();
		return afd.getVendorApplyNum(uid, filter);
	}

	/**
	 * 代理商发起一个新申请，写入applyform表还是redis，it is still a problem!
	 * 
	 * @return
	 */
	public void addNewApply(int uid, String title, String content) {
		try {
			MemCachedClient client = MemDBHelper.getCached();
			JSONObject json = new JSONObject();
			json.put("uid", uid);
			json.put("title", title);
			json.put("content", content);
			client.add(uid+"", json.toString());// auto_increment key，value
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理掉一个未审核的apply
	 * 
	 * @param aid
	 * @param ouid
	 * @param status
	 */
	public void checkApply(int aid, int ouid, int status) {
		try {
			ApplyFormDao afd = new ApplyFormDao();
			MemCachedClient client = MemDBHelper.getCached();
			JSONObject json = new JSONObject(client.get(aid + ""));
			client.delete(aid+"");
			afd.addResolvedApply(json.get("uid"), json.get("title"),
					json.get("content"), ouid, status);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向系统请求分配未审核的apply
	 * @param uid 为0 代表无视用户，申请未审核apply
	 * @return
	 */
	public JSONArray getUncheckedApply(int uid){
		MemCachedClient client = MemDBHelper.getCached();
		return null;
	}
	
	
}
